var crypto = require('crypto');
var JWT = require('jsonwebtoken');
var Config = require('../Config');
var crypto = require("crypto");
var zlib = require('zlib');
module.exports = {
    //账号校验
    isLegitUsername: function (username) {
        if (!username)
            return false;

        //长度不能小于4不能大于12
        var length = username.length;
        if (length == 0)
            return false;

        //昵称不能为纯数字
        if (username.match(/^[0-9]*$/gi))
            return false;

        return true;
    },
    //验证手机号码
    isLegitMobile: function (mobile) {
        if (!mobile)
            return false;

        var length = mobile.length;
        if (length != 11)
            return false;

        //如果不是合法的
        if (!mobile.match(/^[1][3,4,5,7,8,9][0-9]{9}$/g))
            return false;

        return true;
    },
    //加密密码
    md5: function (password) {
        //随机生成MD5码作为token
        var hash = crypto.createHash('md5');
        return hash.update(password).digest('hex');
    },
    jwtDecode: function (string) {
        if (!string)
            return null;
        return JWT.verify(string, Config.jwt.secret);
    },
    jwtEncode: function (string) {
        return JWT.sign(string, Config.jwt.secret);
    },
    // AES 加密
    aesEncrypt: function (string) {
        const cipher = crypto.createCipheriv("aes-128-cbc", Config.aes.key, Config.aes.key);
        let crypted = cipher.update(string, "utf8", "hex");
        crypted += cipher.final("hex");
        return crypted;
    },
    // AES 解密
    aesDecrypt: function (string) {
        const cipher = crypto.createDecipheriv("aes-128-cbc", Config.aes.key, Config.aes.key);
        let decrypted = cipher.update(string, "hex", "utf8");
        decrypted += cipher.final("utf8");
        return decrypted;
    },
    randText: function (len) {
        var baseText = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        var text = "";
        for (var i = 0; i < len; i++)
            text += baseText[Math.floor(Math.random() * baseText.length)];
        return text;
    },
    compress: async function (buffer) {
        return new Promise((resolve, reject) => {
            zlib.gzip(buffer, (err, buffer) => {
                if (err)
                    reject(err);
                else
                    resolve(buffer);
            });
        });
    },
    uncompress: async function (buffer) {
        return new Promise((resolve, reject) => {
            zlib.gunzip(buffer, (err, buffer) => {
                if (err)
                    reject(err);
                else
                    resolve(buffer);
            });
        });
    }
};